package com.dropTables.TakingNote;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.IntentService; 
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;

import android.content.Intent;
import android.content.Context;

import android.location.Location;
import android.location.LocationManager;
import android.location.LocationListener;

import android.os.Bundle;
import android.os.SystemClock;

import android.widget.Toast;

public class GeneralService extends IntentService {
	private static long WAIT_TIME = 5;
	private static ArrayList<String> searchStrings;
	private static ArrayList<Long> ids;
	public GeneralService(){
        super("GeneralService");
    }
	public static void addItem(String item,long id)
	{
		System.out.println("Added Item");
		searchStrings.add(item);
		ids.add(id);
	}
    @Override
      protected void onHandleIntent(Intent intent) {
    	
    	Bundle extras = intent.getExtras();
    	String search = "";
    	long id =1;
    	if(extras!=null)
    	{
    		search = extras.getString("search-string");
    		id = extras.getLong("reminder-id");
    	}
    	if(searchStrings == null)
    		searchStrings = new ArrayList<String>();
    	if(ids == null)
    		ids = new ArrayList<Long>();
    	String location = "";
    	// Acquire a reference to the system Location Manager
    	LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

    	// Define a listener that responds to location updates
    	LocationListener locationListener = new LocationListener() {
    	    public void onLocationChanged(Location location) {
    	      // Called when a new location is found by the network location provider.
    	      //makeUseOfNewLocation(location);
    	    }

    	    public void onStatusChanged(String provider, int status, Bundle extras) {}

    	    public void onProviderEnabled(String provider) {}

    	    public void onProviderDisabled(String provider) {}
    	  };

    	// Register the listener with the Location Manager to receive location updates
    	
    	// Or use LocationManager.GPS_PROVIDER
    	
    	while(true)
    	{
    		try
    		{
	    		//If you get no response wait X minutes before trying again.
    			if(searchStrings.size() == 0)
    			{
    				locationManager.removeUpdates(locationListener);
    			}
    			if(searchStrings.size()>0)
    			{
    				locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
    				String result = "";
    				do
    				{
    					float accuracy = 1000;
    					while(accuracy>50)
    					{
    						Location lastKnownLocation = null;
    						while(lastKnownLocation==null)
    						{
		    			    	lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		    			    	location = lastKnownLocation.getLatitude()+","+lastKnownLocation.getLongitude();
    						}
    						location = lastKnownLocation.getLatitude()+","+lastKnownLocation.getLongitude();
    						if(lastKnownLocation.hasAccuracy())
    							accuracy = lastKnownLocation.getAccuracy();
    					}
    			    	for(int i =0; i<searchStrings.size();i++)
    			    	{
    			    		result = HttpComm.executeHttpNearBy(searchStrings.get(i),location);
    			    		if(!result.equals(""))
    			    		{
    			    			id = ids.get(i);
    			    			search = searchStrings.get(i);
    			    			ids.remove(i);
    			    			searchStrings.remove(i);
    			    			break;
    			    		}
    			    	}
    			    	if(result.equals(""))
    			    		SystemClock.sleep(1000*60*10);
    			    	locationManager.removeUpdates(locationListener);
    				} while (result.equals(""));
		    		
		    		//Create intent
		    		Intent nearByInt = new Intent(this, NearByActivity.class);
		    		
		    		//Parse response using regex
					Pattern p = Pattern.compile(".*?(?<!:):(?!:)");
					Matcher m = p.matcher(result);
					ArrayList<String> input = new ArrayList<String>();
					ArrayList<String> output = new ArrayList<String>();
					while(m.find())
					{
						input.add(m.group());
					}
					for(int i = 0; i<input.size()-1;i+=2)
					{
						String title = input.get(i);
						/*String body = */input.get(i+1);
						
						title = title.replaceAll("(?<!:):(?!:)","");
						title = title.replaceAll("::",":");
						output.add(title);
					}
		    		nearByInt.putExtra("locations",output);
		    		NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
			        long when = System.currentTimeMillis();         // notification time
			        Notification notification = new Notification(R.drawable.tn_icon, "reminder", when);
			        notification.defaults |= Notification.DEFAULT_SOUND;
			        notification.flags |= Notification.FLAG_AUTO_CANCEL;
			        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, nearByInt , 0);
			        notification.setLatestEventInfo(getApplicationContext(), "You're close", "You're next to "+search, contentIntent);
			        nm.notify((int)id, notification);
    			}
    		}
	    	catch(Exception e)
	    	{
	    		e.printStackTrace(System.out);
	    		return;
	    	}
    		SystemClock.sleep(1000*60);
    	}

    }
}